﻿using ShardingCore.Core.EntityMetadatas;
using ShardingCore.Core.VirtualRoutes;
using ShardingCore.VirtualRoutes.Abstractions;

namespace YunQue.Core.DB.ShardingCore
{
    public class TestTableShardRoute :AbstractShardingAutoCreateOperatorVirtualTableRoute<TestTable, string>
    {

        private int _tableCount = 10;//假设分10个表

        /// <summary>
        /// 是否按时间自动创建表，这里哈希分片不需要，所以返回 false
        /// </summary>
        /// <returns></returns>
        public override bool AutoCreateTableByTime()
        {
            return false;
        }
        /// <summary>
        /// 实体分片规则
        /// </summary>
        /// <param name="builder"></param>
        public override void Configure(EntityMetadataTableBuilder<TestTable> builder)
        {
            builder.ShardingProperty(o => o.Id);
        }
        /// <summary>
        /// 定时任务表达式（如果需要自动按时间创建表）
        /// </summary>
        /// <returns></returns>
        public override string[] GetCronExpressions()
        {
            return Array.Empty<string>();
        }
        /// <summary>
        /// 根据查询条件过滤目标表
        /// </summary>
        /// <param name="shardingKey"></param>
        /// <param name="shardingOperator"></param>
        /// <returns></returns>
        public override Func<string, bool> GetRouteToFilter(string shardingKey, ShardingOperatorEnum shardingOperator)
        {
           var tail = ShardingKeyToTail(shardingKey);
            return t => t == tail;
        }
        /// <summary>
        /// 将分片键转换为表尾
        /// </summary>
        /// <param name="shardingKey"></param>
        /// <returns></returns>
        public override string ShardingKeyToTail(object shardingKey)
        {
            var key= shardingKey.ToString();
            int hash = Math.Abs(key.GetHashCode() % _tableCount);
            return hash.ToString();
        }
        /// <summary>
        /// 启动时初始化所有表尾
        /// </summary>
        /// <returns></returns>
        protected override List<string> CalcTailsOnStart()
        {
            return Enumerable.Range(0, _tableCount).Select(i => i.ToString()).ToList();
        }
        /// <summary>
        /// 按时间生成表尾（哈希分片不需要时间，这里随便返回）
        /// </summary>
        /// <param name="now"></param>
        /// <returns></returns>
        protected override string ConvertNowToTail(DateTime now)
        {
            return string.Empty;
        }
    }


}
